package cn.easybuy.util;

import cn.easybuy.pojo.News;
import cn.easybuy.pojo.ProductCategory;
import cn.easybuy.service.news.NewsService;
import cn.easybuy.service.productcategory.ProCategoryService;
import cn.easybuy.vo.ProductCategoryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.ArrayList;
import java.util.List;

/**
 * ServletContext创建调用监听器
 */
//@WebListener
public class ApplicationInit implements ServletContextListener {

    @Autowired
    private NewsService newsService;
    @Autowired
    private ProCategoryService proCategoryService;

    /**
     * ServletContext:创建时调用
     * @param sce
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {

        List<News> news = newsService.list(new QueryWrapper<News>().orderByDesc("createTime").last(" limit 5"));
        List<ProductCategoryVo> productCategoryVoList = new ArrayList<>();
        pcv(0, 1, productCategoryVoList);
        sce.getServletContext().setAttribute("news",news);
        sce.getServletContext().setAttribute("productCategoryVoList",productCategoryVoList);

    }

    //递归
    public void pcv(Integer parentId,Integer type, List<ProductCategoryVo> productCategoryVoList){
        //结束递归的条件
        if(type==4){
            return;
        }
        //重复做的事情
        //1、商品分类
        List<ProductCategory> productCategoryList = proCategoryService.list(new QueryWrapper<ProductCategory>().eq("parentId",parentId).eq("type", type));
        //2、遍历商品分类
        for(ProductCategory productCategory : productCategoryList){
            ProductCategoryVo productCategoryVo = new ProductCategoryVo();
            productCategoryVo.setProductCategory(productCategory);
            //递归调用
            pcv(productCategory.getId(),
                    type+1,productCategoryVo.getProductCategoryVoList());
            productCategoryVoList.add(productCategoryVo);
        }
    }

}
